import java.util.ArrayList;
import java.util.Map;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

public class XImpl extends java.rmi.server.UnicastRemoteObject implements X {

	private Map<String, Double> priceInfo;

	public XImpl() throws java.rmi.RemoteException {
		super();
		priceInfo = new HashMap<String, Double>();
		priceInfo.put("Economic", 200.0);
		priceInfo.put("Semi-Luxe", 400.0);
		priceInfo.put("Luxe", 699.95);
		priceInfo.put("Limusina", 1234.5);

	}

	public ArrayList<Map<String, String>> getTransactions(String username,
			String password) throws java.rmi.RemoteException {

		if (username.equals("admin") && password.equals("password")) {
			ArrayList<Map<String, String>> aux = new ArrayList<Map<String, String>>();
			BufferedReader br = null;
			try {
				br = new BufferedReader(
						new InputStreamReader(new DataInputStream(
								new FileInputStream("lloguers.txt"))));
			} catch (Exception e) {
				System.out.println("getTransactions error: " + e.getMessage());
			}
			String strLine = null;
			try {
				strLine = br.readLine();
			} catch (Exception e) {
				System.out.println("Readline null");
			}
			while (strLine != null) {
				String[] words = strLine.split(" ");
				Map<String, String> t = new HashMap<String, String>();
				t.put("model", words[0]);
				t.put("motor", words[1]);
				t.put("dies", words[2]);
				t.put("quantitat", words[3]);
				t.put("descompte", words[4]);
				t.put("preufinal", words[5]);
				aux.add(t);
				try {
					strLine = br.readLine();
				} catch (Exception e) {
				}
			}
			return aux;
		} else
			return null;
	}

	public double addEntry(Map<String, String> values)
			throws java.rmi.RemoteException {

		// Calcular preu
		Double price = priceInfo.get(values.get("model"));
		price = price == null ? 299.95 : price; // Si no esta al llistat
												// s'assigna el preu per defecte
		price *= values.get("motor").equals("Gasolina") ? 1.1 : 0.9;
		price *= Integer.parseInt(values.get("dies"));
		price *= Integer.parseInt(values.get("quantitat"));
		price -= price * (Double.parseDouble(values.get("descompte")) / 100);

		// Guardar a la 'base de dades'
		BufferedWriter fout;
		try {
			fout = new BufferedWriter(new FileWriter("lloguers.txt", true));
			fout.write(values.get("model") + " " + values.get("motor") + " "
					+ values.get("dies") + " " + values.get("quantitat") + " "
					+ values.get("descompte") + " " + price);
			fout.newLine();
			fout.close();
		} catch (Exception e) {
			System.out.println("addEntry error: " + e.getMessage());
		}
		return price;
	}
}
